# -*- coding: utf-8 -*-
from imp import reload
from flask import render_template, request, jsonify,redirect,session,url_for
from app.main.sessions import load_sessions ,load_sessions3
from ..hostel.sessions import load_sessions2
from . import main
from app.models import UserInfo, UserInfo13per, Teacher,Lessons, Log
from app.posttext import get_result
from app.postname import get_result2
from config import Config
from .xiaosi_models import Openid,location
from ..hostel.models import SchoolCard
from app.user_login import get_user
import sys
import datetime
reload(sys)
sys.setdefaultencoding('utf8')


@main.route('/firstpage')
def get_list():
    user_id = session.get('user_id')
    if not user_id:
        return redirect(url_for('main.get_login'))
    # 以上3行可以使浏览器失效
    authority = 1
    user = session.get('user_name')
    my_pow =0
    # if user_id == '20181101125':
    #     my_pow =2
    if authority == 1:
        return render_template('Firstpage.html',authority=authority,my_pow=my_pow,user_id=user_id,user=user)

@main.route('/search_info')
def get_search():
    user_id = session.get('user_id')
    if not user_id:
        return redirect(url_for('main.get_login'))
    # 以上3行可以使浏览器失效
    user = session.get('user_name')
    user_department = session.get('user_department')
    authority = 0
    if Config.FuDaoYuanID in user_department:
        authority = 1
    session['authority2'] = authority
    if authority == 1  or authority == 0:
        return render_template('search.html',user=user,authority=authority,user_department=user_department)
    else:
        return render_template('nofound.html')


@main.route('/search_handle', methods=['GET', 'POST'])
def search_result():
    if request.method == 'POST':
        search_text = request.form.get('text')
        sessions = load_sessions()
        # 判断文字类型
        if search_text.isdigit():
            result = sessions.query(UserInfo).filter(UserInfo.studentId == search_text).all()
        else:
            result = sessions.query(UserInfo).filter(UserInfo.Name.like('%'+search_text+'%')).all()
        sessions.close()
        if result:
            count = len(result)
            result_list = []
            for info in result:
                info_dict = {'name': info.Name, 'sno': info.studentId, 'class_': info.ClassName}
                result_list.append(info_dict)
            return jsonify({'count': count, 'info': result_list})
        else:
            return jsonify({'count': 0})


@main.route('/detail')
def get_detail():
    user_id = session.get('user_id')
    if not user_id:
        return redirect(url_for('main.get_login'))
    user = session.get('user_name')
    uid = request.args.get('uid')
    sessions = load_sessions()
    result = sessions.query(UserInfo).filter(UserInfo.studentId == uid).first()
    sessions.close()
    sessions = load_sessions()
    postschool = sessions.query(UserInfo13per).filter(UserInfo13per.studentId == uid).first()
    sessions.close()
    minzu = get_result2(uid)
    return render_template('result.html', result=result,minzu=minzu,postschool=postschool,user=user)


@main.route('/score')
def score():
    user_id = session.get('user_id')
    if not user_id:
        return redirect(url_for('main.get_login'))
    user = session.get('user_name')
    uid = request.args.get('uid')
    result = get_result(uid)
    result2 = get_result2(uid)
    return render_template('score.html', result=result,result2=result2,user=user)


@main.route('/login')
def get_login():
    return redirect(
        Config.GET_CODE.format(APP_ID=Config.CORPID, REDIRECT_URL='http://jza.gangxi.xiaosikeji.com/redirect', AGENT_ID=Config.AGENTID))


@main.route('/redirect')
def get_redirect_index():
    code = request.args.get('code')
    get_user(code)
    return redirect(url_for('main.get_list'))


@main.route('/mainpage')
def get_info():
    user_id = session.get('user_id')
    if not user_id:
        return redirect(url_for('main.get_login'))
    uid = request.args.get('uid')
    user = session.get('user_name')
    power = session.get('authority2')
    get_record(uid)
    sessions = load_sessions()
    result = sessions.query(UserInfo).filter(UserInfo.studentId == uid).first()
    sessions.close()
    sessions = load_sessions()
    classname = sessions.query(UserInfo.ClassName).filter(UserInfo.studentId == uid).first()
    sessions.close()
    sessions = load_sessions()
    ID = sessions.query(Lessons.TeacherId).filter(Lessons.ClassName == classname).first()
    counsellor = sessions.query(Teacher).filter(Teacher.TeacherId == ID).first()
    sessions.close()
    sessions = load_sessions3()
    open_id = sessions.query(Openid.openid).filter(Openid.uid == uid).first()
    is_latitude = sessions.query(location.latitude).filter(location.openid == open_id).first()
    sessions.close()
    location_pow = 1
    if open_id == None or is_latitude == None:
        location_pow =0
    return render_template('main.html',uid=uid,user=user,result=result,counsellor=counsellor,power=power,location_pow=location_pow)


@main.route('/sessionclear')
def clear():
    session.clear
    return 'OK'


#  记录日志
@main.route('/record')
def get_record(uid):
    now_time = datetime.datetime.now().strftime('%F %T')
    user = session.get('user_name')
    sessions = load_sessions()
    log1 = Log(content=uid, selecttime=now_time, inputuser=user)
    sessions.add(log1)
    sessions.commit()
    sessions.close()
    return 'ok'

# 定位
@main.route('/location',  methods=['GET', 'POST'])
def get_jwd():
    user_id = session.get('user_id')
    if not user_id:
        return redirect(url_for('main.get_login'))
    user_id = request.args.get('uid')
    sessions = load_sessions3()
    open_id = sessions.query(Openid.openid).filter(Openid.uid == user_id).first()
    print open_id
    location_list = sessions.query(location).filter(location.openid == open_id).first()
    sessions.close()
    return render_template('location.html',location_list=location_list)

# 楼宇记录
@main.route('/selfhostel', methods=['GET', 'POST'])
def self_hostel():
    username = request.args.get('username')
    user_id = request.args.get('userid')
    nowTime = datetime.datetime.now().strftime('%Y-%m-%d')
    sessions = load_sessions2()
    self_list = sessions.query(SchoolCard).filter(SchoolCard.idserial == user_id,SchoolCard.acctime.like("%"+nowTime[:7]+"%")).order_by(SchoolCard.acctime.desc()).all()
    sessions.close()
    print self_list
    return render_template('self_hostel.html',self_list=self_list,username=username)
